package res;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.util.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
//使用注解 就不用在web.xml里面再配置了 只有一个urlPatterns属性时, 属性名也可以省略
// urlPatterns = { "/myServlet", "/myServlet4" }  多个urlPatterns也可以的
@WebServlet(name = "ServletForm",urlPatterns = "/sf")
public class ServletForm extends HttpServlet {

    protected void doOptions(HttpServletRequest request, HttpServletResponse response) {

    /* 允许跨域的主机地址 */
//    response.setHeader("Access-Control-Allow-Origin", "*");//http://172.20.0.206 指定某个地址
    /* 允许跨域的请求方法GET, POST, HEAD 等 */
//    response.setHeader("Access-Control-Allow-Methods", "*");
    /* 重新预检验跨域的缓存时间 (s) */
//    response.setHeader("Access-Control-Max-Age", "60");
    /* 允许跨域的请求头 */
//    response.setHeader("Access-Control-Allow-Headers", "*");
    /* 是否携带cookie 是否允许后续请求携带认证信息（cookies）,该值只能是true,否则不返回 */
//    response.setHeader("Access-Control-Allow-Credentials", "true");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // post方式测试
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        System.out.println("post请求");
//        用于设置 Servlet 输出内容的 类型以及编码格式。
        response.setContentType("text/html;charset=UTF-8");
//        用于设置拿到的参数使用的字符编码。
        request.setCharacterEncoding("utf-8");
//        用于设置输出内容使用的字符编码。
        response.setCharacterEncoding("utf-8");
        PrintWriter out = response.getWriter();
        Map<String, Object> params = new HashMap<>();
        try {
            // 获取了json数据
            String paramJson = IOUtils.toString(request.getInputStream());
            System.out.println("paramJson"+paramJson);
            JSONObject jsonObject = JSONObject.parseObject(paramJson);
            System.out.println(paramJson);
            System.out.println(jsonObject.getString("purId"));
            System.out.println(jsonObject.getString("replyContent"));
            System.out.println(jsonObject.getString("commentId"));

            Map parseObject = JSON.parseObject(paramJson, Map.class);
            params.putAll(parseObject); // map
            System.out.println("paramsMap:"+params);
            String jsonString = JSON.toJSONString(params); // map =>string
            System.out.println("jsonString"+jsonString);
            JSONObject paramsjson = new JSONObject(params);   //map =>JSON
            System.out.println("paramsjson"+paramsjson);


        } catch (Exception e) {
            e.printStackTrace();
        }

        String str="[{\"age\":152,\"fullName\":\"John Doe\"},{\"age\":202,\"fullName\":\"Janette Doe\"}]";
        // 这里里面最好是json数据
        out.write(str);
        out.write(str);

        out.flush();
        out.close();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // get 方式测试
        // 设置响应内容类型
   /*      设置浏览器打开文件时编码
        response.setHeader("Content-Type", "text/html;charset=UTF-8");*/
//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Methods", "*");
        System.out.println("get请求");
        // 处理中文乱码
        response.setContentType("text/html;charset=UTF-8");

        PrintWriter out = response.getWriter();

        // 处理中文
//        String name =new String(request.getParameter("name").getBytes("ISO-8859-1"),"UTF-8");

        request.setCharacterEncoding("utf-8");
        //设置返回类型为json，字符集为utf-8
        response.addHeader("content-type", "text/json;charset=utf-8");
        // 据键名获取键值
        String userName = request.getParameter("username");
        String password = request.getParameter("password");
//        String[] test  = request.getParameterValues("test");

        System.out.println(userName + "\t" + password);

        // 目前这里是手拼的json数据, 可以使用json转换工具
        String str="[{\"age\":15,\"fullName\":\"John Doe\"},{\"age\":20,\"fullName\":\"Janette Doe\"}]";

        /* 这里里面最好是json数据*/
        out.write(str);
//        out.println("你好");
        // get请求里面写out.println 会出错  post里面写的 会返给前端

        out.flush();
        out.close();
    }
}
      /*  out.println("请求方式:" + request.getMethod() + "<br/>" +
                "客户端的 IP 地址:" + request.getRemoteAddr() + "<br/>" +
                "应用名字（上下文）:" + request.getContextPath() + "<br/>" +
                "URI:" + request.getRequestURI() + "<br/>" +
                "请求字符串:" + request.getQueryString() + "<br/>" +
                "Servlet所映射的路径:" + request.getServletPath() + "<br/>" +
                "客户端的完整主机名:" + request.getRemoteHost() + "<br/>");   */

/**
   前端把数据发给servlet =>  servlet层调用 serviceImpl方法  =>
   serviceImpl层的方法 调用对应的DaoImpl方法  => DaoImpl方法 实现数据库的crud
 */


